Make uri_expand handle any object

Akinori MUSHA 9 years ago
parent
commit
01219153bd
2 changed files with 24 additions and 1 deletions
  1. 12 1
      app/concerns/liquid_interpolatable.rb
  2. 12 0
      spec/concerns/liquid_interpolatable_spec.rb

+ 12 - 1
app/concerns/liquid_interpolatable.rb

@@ -141,7 +141,17 @@ module LiquidInterpolatable
141 141
     # occurs while following redirects, the last URL followed is
142 142
     # returned.
143 143
     def uri_expand(url, limit = 5)
144
-      uri = URI(url)
144
+      case url
145
+      when URI
146
+        uri = url
147
+      else
148
+        url = url.to_s
149
+        begin
150
+          uri = URI(url)
151
+        rescue URI::Error
152
+          return url
153
+        end
154
+      end
145 155
 
146 156
       http = Faraday.new do |builder|
147 157
         builder.adapter :net_http
@@ -153,6 +163,7 @@ module LiquidInterpolatable
153 163
         begin
154 164
           case uri
155 165
           when URI::HTTP
166
+            return uri.to_s unless uri.host
156 167
             response = http.head(uri)
157 168
             case response.status
158 169
             when 301, 302, 303, 307

+ 12 - 0
spec/concerns/liquid_interpolatable_spec.rb

@@ -116,6 +116,18 @@ describe LiquidInterpolatable::Filters do
116 116
         to_return(status: 301, headers: { 'Content-Length' => '5' })
117 117
     end
118 118
 
119
+    it 'should handle inaccessible URIs' do
120
+      expect(@filter.uri_expand(nil)).to eq('')
121
+      expect(@filter.uri_expand('')).to eq('')
122
+      expect(@filter.uri_expand(5)).to eq('5')
123
+      expect(@filter.uri_expand([])).to eq('[]')
124
+      expect(@filter.uri_expand({})).to eq('{}')
125
+      expect(@filter.uri_expand(URI('/'))).to eq('/')
126
+      expect(@filter.uri_expand(URI('http:google.com'))).to eq('http:google.com')
127
+      expect(@filter.uri_expand(URI('http:/google.com'))).to eq('http:/google.com')
128
+      expect(@filter.uri_expand(URI('ftp://ftp.freebsd.org/pub/FreeBSD/README.TXT'))).to eq('ftp://ftp.freebsd.org/pub/FreeBSD/README.TXT')
129
+    end
130
+
119 131
     it 'should follow redirects' do
120 132
       expect(@filter.uri_expand('https://t.co.x/aaaa')).to eq('http://www.example.com/welcome')
121 133
     end